package com.cqeec.myblog.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/captcha.html")
public class CaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = -8528865119392832891L;
	private static final String CHAR = "0123456789";
	private static final int WIDTH = 200;
	private static final int HEIGHT = 38;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		char[] code = new char[4];
		// 生成验证码图片的响应设置
		// 设置页面缓存
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		// 网页缓存过期时间
		response.setDateHeader("Expires", 0);
		// 设置响应内容类型
		response.setContentType("image/jpeg");

		Random r = new Random();

		// 随机生成验证码
		for (int i = 0; i < 4; i++) {
			code[i] = CHAR.charAt(r.nextInt(CHAR.length()));
		}
		// 将验证码放入会话对象用于登录时进行验证
		request.getSession().setAttribute("code", String.valueOf(code));
		// 通过BufferedImage生成图片，并绘制背景
		BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
		Graphics g = bi.getGraphics();
		g.fillRect(0, 0, WIDTH, HEIGHT);
		// 干扰线
		for (int i = 1; i <= 10; i++) {
			g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
			g.drawLine(r.nextInt(WIDTH), r.nextInt(HEIGHT), r.nextInt(WIDTH), r.nextInt(HEIGHT));
		}
		// 将生成验证码的每个字符以不同的颜色绘到图片上
		g.setFont(new Font("隶书", Font.BOLD, 36));
		for (int i = 0, x = 10; i < 4; i++, x += 50) {
			g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
			g.drawString(code[i] + "", x, 30);
		}
		// 通过response对象将验证码图片发送到客户端浏览器
		ImageIO.write(bi, "jpg", response.getOutputStream());
	}

}
